package com.fortune.rainshineservice.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.entity.StatTopTenEntity;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.*;
import com.fortune.rainshinecommon.util.DateUtils;
import com.fortune.rainshineservice.mapper.*;
import com.fortune.rainshineservice.service.StatService;
import com.google.common.collect.Lists;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @program: rainShine
 * @description:
 * @author: tangyn
 * @create: 2019-06-15
 **/
@Service
public class StatServiceImpl implements StatService {
    private static final Logger logger = LoggerFactory.getLogger(StatServiceImpl.class);

    private final MonthShopStatMapper monthShopStatMapper;
    private final ShopMapper shopMapper;
    private final CustomerMapper customerMapper;
    private final CustomerServiceRecordMapper customerServiceRecordMapper;
    private final StockRecordsMapper stockRecordsMapper;
    private final DayShopStatMapper dayShopStatMapper;
    private final DayProductStatMapper dayProductStatMapper;
    private final DayServiceStatMapper dayServiceStatMapper;
    private final MonthProductStatMapper monthProductStatMapper;
    private final MonthServiceStatMapper monthServiceStatMapper;

    @Autowired
    public StatServiceImpl(MonthShopStatMapper monthShopStatMapper, ShopMapper shopMapper, CustomerMapper customerMapper,
                           CustomerServiceRecordMapper customerServiceRecordMapper, StockRecordsMapper stockRecordsMapper,
                           DayShopStatMapper dayShopStatMapper, DayProductStatMapper dayProductStatMapper,
                           DayServiceStatMapper dayServiceStatMapper, MonthProductStatMapper monthProductStatMapper,
                           MonthServiceStatMapper monthServiceStatMapper) {
        this.monthShopStatMapper = monthShopStatMapper;
        this.shopMapper = shopMapper;
        this.customerMapper = customerMapper;
        this.customerServiceRecordMapper = customerServiceRecordMapper;
        this.stockRecordsMapper = stockRecordsMapper;
        this.dayShopStatMapper = dayShopStatMapper;
        this.dayProductStatMapper = dayProductStatMapper;
        this.dayServiceStatMapper = dayServiceStatMapper;
        this.monthProductStatMapper = monthProductStatMapper;
        this.monthServiceStatMapper = monthServiceStatMapper;
    }

    @Override
    public List<StatTopTenEntity> selectMerchatStat(String beginTime, String endTime) {
        return monthShopStatMapper.selectMerchatStat(beginTime,endTime);
    }

    @Override
    public List<StatTopTenEntity> getShopNewCustomerStat(String beginTime, String endTime) {
        return monthShopStatMapper.getShopNewCustomerStat(beginTime,endTime);
    }

    @Override
    public List<StatTopTenEntity> getShopBuyStat(String beginTime, String endTime) {
        return monthShopStatMapper.getShopBuyStat(beginTime,endTime);
    }

    @Override
    @Transactional
    public MsgModel dayReRun() {
        try{
            Date startDate = DateUtils.parse("2019-01-30", DateUtils.YYYY_MMM_DD);
            Date endDate = new Date();
            List<String> dateList = DateUtils.getDates(startDate, endDate);
            for(String date : dateList){
                stateDayShop(date);
            }
            for(String date : dateList){
                statDayProduct(date);
            }
            for(String date : dateList){
                statDayService(date);
            }
            //修改商铺表的统计时间
            Wrapper<ShopModel> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_status", 1);
            List<ShopModel> shopModelList = Optional.ofNullable(shopMapper.selectList(wrapper)).orElse(Lists.newArrayList());
            for(ShopModel s : shopModelList){
                s.setStatDate(endDate);
                shopMapper.updateById(s);
            }
        }catch (Exception e){
            logger.error("day reRun Exception ====> {}", e);
            return new MsgModel(ResultCode.FAILURE, e.getMessage());
        }
        return new MsgModel(ResultCode.SUCCESS);
    }

    @Override
    @Transactional
    public MsgModel monthReRun() {
        try{
            Date startDate = DateUtils.parse("2019-06-30", DateUtils.YYYY_MMM_DD);
            int betweenNum = DateUtils.timeBetweenMonth(new DateTime(startDate), DateTime.now());
            DateTime lastMonth = new DateTime(startDate);
            for (int i = 0; i < betweenNum; i++) {
                Date statDate = DateUtils.parse(DateUtils.format(lastMonth.toDate(),DateUtils.YYYY_MMM_DD), null);
                DateTime cTime = new DateTime(statDate);
                monthShopStat(statDate, cTime);
                monthProductStat(statDate, cTime);
                monthServiceStat(statDate, cTime);
                lastMonth = lastMonth.plusMonths(1);
            }
            //修改法院信息表的统计时间
            Wrapper<ShopModel> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_status", 1);
            List<ShopModel> shopModelList = Optional.ofNullable(shopMapper.selectList(wrapper)).orElse(Lists.newArrayList());
            for(ShopModel s : shopModelList){
                s.setStatMonth(DateUtils.parse(DateUtils.format(lastMonth.toDate(),DateUtils.YYYY_MMM_DD), null));
                shopMapper.updateById(s);
            }
        }catch (Exception e){
            logger.error("month reRun Exception ====> {}", e);
            return new MsgModel(ResultCode.FAILURE, e.getMessage());
        }
        return new MsgModel(ResultCode.SUCCESS);
    }

    @Override
    public void monthServiceStat(Date date,DateTime cTime) {
        List<MonthServiceStatModel> list = dayServiceStatMapper.statMonth(DateUtils.format(date,DateUtils.YYYY_MMM));
        if (list.isEmpty()) {
            return;
        }
        for(MonthServiceStatModel m : list){
            m.setStatYear(cTime.getYear());
            m.setStatMonth(cTime.getMonthOfYear());
            m.setStatDate(date);
            m.setCreateTime(new Date());
            monthServiceStatMapper.insertSelective(m);
        }
    }

    @Override
    public void monthProductStat(Date date, DateTime cTime) {
        List<MonthProductStatModel> list = dayProductStatMapper.statMonth(DateUtils.format(date,DateUtils.YYYY_MMM));
        if (list.isEmpty()) {
            return;
        }
        for(MonthProductStatModel m : list){
            m.setStatYear(cTime.getYear());
            m.setStatMonth(cTime.getMonthOfYear());
            m.setStatDate(date);
            m.setCreateTime(new Date());
            monthProductStatMapper.insert(m);
        }
    }

    @Override
    public void monthShopStat(Date date, DateTime cTime) {
        List<MonthShopStatModel> list = dayShopStatMapper.statMonth(DateUtils.format(date,DateUtils.YYYY_MMM));
        if (list.isEmpty()) {
            return;
        }
        for(MonthShopStatModel m: list){
            m.setStatYear(cTime.getYear());
            m.setStatMonth(cTime.getMonthOfYear());
            m.setStatDate(date);
            m.setCreateTime(new Date());
            monthShopStatMapper.insertSelective(m);
        }
    }

    @Override
    public void statDayService(String date) {
        List<DayServiceStatModel> list = customerServiceRecordMapper.getDayService(date);
        if (list.isEmpty()) {
            return;
        }
        for(DayServiceStatModel m : list){
            DateTime cTime = new DateTime(date);
            m.setStatYear(cTime.getYear());
            m.setStatMonth(cTime.getMonthOfYear());
            m.setStatDay(cTime.getDayOfMonth());
            m.setStatDate(DateUtils.parse(date,null));
            m.setCreateTime(new Date());
            dayServiceStatMapper.insert(m);
        }
    }

    @Override
    public void statDayProduct(String date) {
        List<DayProductStatModel> list = stockRecordsMapper.getStatDayProduct(date);
        if (list.isEmpty()) {
            return;
        }
        for(DayProductStatModel m : list){
            DateTime cTime = new DateTime(date);
            m.setStatYear(cTime.getYear());
            m.setStatMonth(cTime.getMonthOfYear());
            m.setStatDay(cTime.getDayOfMonth());
            m.setStatDate(DateUtils.parse(date,null));
            m.setCreateTime(new Date());
            dayProductStatMapper.insert(m);
        }
    }

    @Override
    public void stateDayShop(String date) {
        List<DayShopStatModel> list = Lists.newArrayList();
        //新增会员数量
        list.addAll(customerMapper.getNewCustomerNum(date));
        //服务次数
        list.addAll(customerServiceRecordMapper.getServerTimes(date));
        //采购产品总价值
        list.addAll(stockRecordsMapper.getTotalPrice(date, 1));
        //出货产品总价值
        list.addAll(stockRecordsMapper.getTotalPrice(date, 2));

        if (list.isEmpty()) {
            return;
        }
        try {
            Map<Integer, List<DayShopStatModel>> mapList = list.stream()
                    .collect(Collectors.groupingBy(DayShopStatModel::getShopId));
            for(Integer key : mapList.keySet()){
                List<DayShopStatModel> newList = mapList.get(key);
                Map<Integer, List<DayShopStatModel>> mList = newList.stream()
                        .collect(Collectors.groupingBy(DayShopStatModel::getShopId));
                for(Integer k : mList.keySet()){
                    List<DayShopStatModel> resultList = mList.get(k);
                    DayShopStatModel sbcd = new DayShopStatModel();
                    for (DayShopStatModel s : resultList){
                        if(s.getShopId() != null){
                            sbcd.setShopId(s.getShopId());
                        }
                        if(s.getShopLevel() != null){
                            sbcd.setShopLevel(s.getShopLevel());
                        }
                        if(s.getBuyTotalPrice() != null){
                            sbcd.setBuyTotalPrice(s.getBuyTotalPrice());
                        }
                        if(s.getSaleTotalPrice() != null){
                            sbcd.setSaleTotalPrice(s.getSaleTotalPrice());
                        }
                        if(s.getNewCount() != null){
                            sbcd.setNewCount(s.getNewCount());
                        }
                        if(s.getServerTimes() != null){
                            sbcd.setServerTimes(s.getServerTimes());
                        }
                    }
                    DateTime cTime = new DateTime(date);
                    sbcd.setStatYear(cTime.getYear());
                    sbcd.setStatMonth(cTime.getMonthOfYear());
                    sbcd.setStatDay(cTime.getDayOfMonth());
                    sbcd.setStatDate(DateUtils.parse(date,null));
                    sbcd.setCreateTime(new Date());
                    dayShopStatMapper.insertSelective(sbcd);
                }
            }
        }catch (Exception e){
            logger.error("门店统计日表异常", e);
        }
    }
}
